import formatTime from "../../utils/util.js"
const app = getApp()
wx.cloud.init({env:"pethub-database"})
const db = wx.cloud.database().collection('user')
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  // 0:条目名称，1：进度条比例，2：行为倒计时，3: 行为的时间间隔，4：所属父级字段，5：数组中索引值
  // 主要用于前端渲染数据
  record:[],
  timeLine:[],
  id:'',
  pet:"",
  long:false,
  humanAge:"",
  // 时间轴相关控件的事件
  input:function(e){
    this.setData({order:e.currentTarget.dataset.index})
  },
  blur: function (e) {
    this.setData({ order: null })
  },
  write:function(e){
    // 要注意列表渲染反序而数组存储还是原来的顺序，所以
    var index = this.timeLine.length-1-e.detail.target.dataset.index
    var record = "records." + index+".4"
    this.timeLine[e.detail.target.dataset.index][4] = e.detail.value.daily
    this.setData({ timeLine: this.timeLine, order: null })
    db.doc(this.id).update({
      data:{
        [record]: e.detail.value.daily
      }
    }).then()
  },

  changeGif:function(src){
    this.setData({gif:src})
  },

  clickPet:function(){
    this.changeGif("cloud://pethub-database.7065-pethub-database-1301811252/gif/" + this.pet + "-static.gif")
    wx.showToast({
      title: '别碰我怕痒٩(ŏ﹏ŏ,)۶',
      icon:'none'
    })
    setTimeout(this.changeGif, 1500, "cloud://pethub-database.7065-pethub-database-1301811252/gif/" + this.pet + "-default.gif")
  },

  // 首页按钮
  setting:function(e){
    var goal = this.record[e.currentTarget.dataset.index]
    var command = goal[4]+"."+goal[5].toString()+".date"
    var day = formatTime.formatTime(new Date())
    var t = day.split(' ')[0].split("-")
    // 数组反序确保最新事件显示在上方
    this.timeLine.reverse().push([t[0], t[1], t[2], day.split(' ')[1],goal[0]])
    // 更新上次操作日期和添加用户操作记录
    db.doc(this.id).update({
      data: {
      // 云数据库sdk，变量字段的写法
        [command]:formatTime.formatTime(new Date()).split(' ')[0],
        records:this.timeLine
      }
    })
    // 更新指定记录
    this.record[e.currentTarget.dataset.index][1]='100%'
    this.record[e.currentTarget.dataset.index][2] = this.record[e.currentTarget.dataset.index][3]
    this.setData({ data: this.record, timeLine: this.timeLine.reverse(), gif: "cloud://pethub-database.7065-pethub-database-1301811252/gif/"+this.pet+"-happy.gif"})
    // 切换动图，展现宠物状态
    setTimeout(this.changeGif, 2000, "cloud://pethub-database.7065-pethub-database-1301811252/gif/" + this.pet + "-default.gif")
    wx.showToast({
      title: '谢谢主人(ฅ´ω`ฅ)',
      icon:"none"
    })
  },

  human:function(int,date){
    if(date=="岁"){
      if(int==1){this.humanAge ="15岁"}
      else if(int==2){this.humanAge = "24岁"}
      else{
        if(this.pet="cat"){
          this.humanAge = ((int-2)*4+24).toString()+"岁"
        }
        else{
          this.humanAge = ((int - 2) * 5 + 24).toString() + "岁"
        }
      }
    }
    else if(date=="月"){
      this.humanAge=parseInt(int+1).toString()+"岁"
    }
    else{
      this.humanAge = parseInt(int+1).toString() + "月"
    }
  },

  // 将天数的年龄转为字符串的年龄
  convertStr:function(days){
    var age = ''
    if(days>360){
      age=parseInt(days/360).toString()+"岁"
      this.human(parseInt(days / 360),"岁")
      }
    // 月份的days范围不用改
    else if(days>=28 && days <=360){
      age=parseInt(days/28)+"月"
      this.human(parseInt(days / 28),"月")
      }
    else { 
      age = parseInt(days / 7) + "周"
      this.human(parseInt(days / 7),"周")
      }
    return age
  },

  render:function(data,field,index){
    var today = app.toDays(formatTime.formatTime(new Date()).split(' ')[0])
    var last = app.toDays(data[field][index]["date"])
    // 使用小程序当天与上次操作时间的相隔天数
    var diff = today - last

    // 行为倒计时与时长间隔的比例，主要用于进度条
    var length = 1 - (diff / parseInt(data[field][index]["slider"]))

    // 表示用户操作还未超出时间范围
    if (parseInt(data[field][index]["slider"]) - diff > 0) {
      this.record.push(
        [data[field][index]["name"],
        (length * 100).toString().substring(0, 5) + "%",
        parseInt(data[field][index]["slider"]) - diff, // 计算行为倒计时的天数
        data[field][index]["slider"],
        field, index
        ])
    }

    // 表示用户已经很久没做这件事了
    else {
      this.long = true
      this.record.push([data[field][index]["name"], "100%", parseInt(data[field][index]["slider"]) - diff, data[field][index]["slider"], field, index])
    }
    return this.record
  },

  getData:function(openid){
    var field = ['richang', 'toubu', 'xiabanshen', 'qita']

    db.where({ _openid: openid }).get().then(res => {
      //console.log("res.data"+res.data[0]["_openid"])
      // 数据库找不到这个用户的数据，那就是该用户初次使用，先要他跳转到初次加载页
      if (res.data.length == 0) {
        wx.showToast({
          title: '新手上路，请跟我来',
          icon:"none"
        })
        wx.reLaunch({
          url: '/pages/firstLoad/firstLoad',
        })
      }
      this.pet = res.data[0]["pet"]
      this.timeLine = res.data[0]["records"].reverse()
      wx.setStorageSync("_id", res.data[0]["_id"])
      this.id = res.data[0]["_id"]
      
      if(!wx.getStorageSync("isshow")){
        var isshow = { 'richang':[], 'toubu':[], 'xiabanshen':[], 'qita':[]}
        // 双层循环嵌套，遍历可显示条目
        for (var i = 0; i < field.length; i++) {
          for (var ii = 0; ii < res.data[0][field[i]].length; ii++) {
            if (res.data[0][field[i]][ii]["isshow"]) {
              isshow[field[i]].push(ii)
              this.render(res.data[0], field[i],ii)
            }
          }
        }
        wx.setStorageSync("isshow", isshow)
      }
      else{ 
        var isshow = wx.getStorageSync("isshow")
        for (var i = 0; i < field.length; i++){
          for (var ii = 0; ii < isshow[field[i]].length; ii++){
            this.render(res.data[0], field[i], isshow[field[i]][ii])
          }
        }
      }

      // 计算上次登录与本次登录的时间差
      if (app.toDays(formatTime.formatTime(new Date()).split(" ")[0]) - app.toDays(wx.getStorageSync("lastTime")) >= 5 || this.long) {
        var gif = 'cloud://pethub-database.7065-pethub-database-1301811252/gif/' + this.pet + '-sad.gif'
        wx.showToast({
          title: '主人好久没理我了(ノへ￣,)',
          icon: "none"
        })
      }
      else { var gif = 'cloud://pethub-database.7065-pethub-database-1301811252/gif/' + this.pet + '-default.gif' }

      this.setData({
        data: this.record,
        info: res.data[0],
        timeLine: this.timeLine,
        age: this.convertStr(res.data[0]['age']),
        gif: gif,
        id: wx.getStorageSync("openid"),
        human:this.humanAge
      })

      // 每次登录都要记得更新记录上次登录时间的缓存
      wx.setStorageSync("lastTime", formatTime.formatTime(new Date()).split(" ")[0])
    })

  },

  onLoad: function (options) {
    let that = this
    // 确保openid缓存一定有
    if (!wx.getStorageSync("openid")) {
  // 因为在删除缓存后，再立刻调用app.getOpenid()无法正常返回值，所以只好直接在onload调云函数
  // 封装了请求云数据库、传数据给前端的逻辑，直接在回调函数中执行
      wx.cloud.callFunction({
        name: "login",
        success(res) {
          console.log("cloudFuction"+res.result.openid)
          wx.setStorageSync("openid", res.result.openid)
          that.getData(res.result.openid)
        },
        fail(err) {
          wx.showToast({
            title: '对不起出错了,请关闭小程序重新登录试试',
            icon: "none"
          })
          console.log("云服务器忙或调用达到上限！")
          console.log("错误原因：" + err)
        }
      })
      }
    else{
      that.getData(wx.getStorageSync("openid"))
    }

  },
})